//
//  M_AddressSelView.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/8.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_AddressSelView: UIView {
    //定义一个闭包类型
    typealias selectBlock = (_ selarr : M_AddressSelView) -> Void
    //声明一个变量
    var callBack: selectBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callSelBlock(block: @escaping selectBlock) {
        callBack = block
    }
    
    var nodeViwe1:OA_Tree_SingView = OA_Tree_SingView()
    var nodeViwe2:OA_Tree_SingView = OA_Tree_SingView()
    var nodeViwe3:OA_Tree_SingView = OA_Tree_SingView()
    var nodeViwe4:OA_Tree_SingView = OA_Tree_SingView()
    
    let nodeViweLab1 = UILabel()
    let nodeViweLab2 = UILabel()
    let nodeViweLab3 = UILabel()
    let nodeViweLab4 = UILabel()
    
    var provinceCode = [String:Any?]()
    var cityCode = [String:Any?]()
    var districtCode = [String:Any?]()
    var townCode = [String:Any?]()

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    override func draw(_ rect: CGRect) {
        let bgview = UIView(frame: CGRect(x: 0, y: rect.height/2, width: rect.width, height: rect.height/2))
        self.addSubview(bgview)
        bgview.drawLabel(text: "选择地址", fontSize: 16, textColor: .x333333) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(35)
        }
        bgview.backgroundColor = .white
        
        let btn = bgview.drawButton(imageNamed: "guanbi_84") { (make) in
            make.top.equalTo(10)
            make.right.equalTo(-10)
        }
        btn.addTarget(self, action: #selector(_closeButtonClick(button:)), for: .touchUpInside)
        btn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        
        var btmview = nodeViweLab1.drawView { (make) in
            make.top.equalTo(nodeViweLab1.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(2.5)
        }
        btmview.backgroundColor = .xFC4C02
        
        btmview = nodeViweLab2.drawView { (make) in
            make.top.equalTo(nodeViweLab2.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(2.5)
        }
        btmview.backgroundColor = .xFC4C02
        
        btmview = nodeViweLab3.drawView { (make) in
            make.top.equalTo(nodeViweLab3.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(2.5)
        }
        btmview.backgroundColor = .xFC4C02
        
        btmview = nodeViweLab4.drawView { (make) in
            make.top.equalTo(nodeViweLab4.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(2.5)
        }
        btmview.backgroundColor = .xFC4C02
        
        bgview.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(90+1.0)
            make.height.equalTo(0.5)
        }.backgroundColor = .xD1D1D1
        
        ///加载地址树
        getGetProvinceList(callback: { (list) in
            self.nodeViwe1.nameKey = "provinceName"
            bgview.drawView(view: self.nodeViwe1) { (make) in
                make.left.equalToSuperview()
                make.width.equalTo(90)
                make.top.equalToSuperview().offset(90)
                make.bottom.equalToSuperview()
            }
            self.nodeViwe1.titleArr = list
            bgview.drawLabel(label: self.nodeViweLab1, text: "请选择", fontSize: 13, fontWeight: .regular, textColor: .x333333) { (make) in
                make.bottom.equalTo(self.nodeViwe1.snp.top)
                make.centerX.equalTo(self.nodeViwe1)
            }
        })
        nodeViwe1.callSelBlock(block: { (sel) in
            self.provinceCode = sel
            self.getGetCityList(provinceID: sel.getString("provinceID") ?? "", callback: { (list) in
                self.nodeViwe2.nameKey = "cityName"
                bgview.drawView(view: self.nodeViwe2) { (make) in
                    make.left.equalTo(self.nodeViwe1.snp.right)
                    make.width.equalTo(80)
                    make.top.equalToSuperview().offset(90)
                    make.bottom.equalToSuperview()
                }
                self.nodeViwe2.titleArr = list
                bgview.drawLabel(label: self.nodeViweLab2, text: "请选择", fontSize: 13, fontWeight: .regular, textColor: .x333333) { (make) in
                    make.bottom.equalTo(self.nodeViwe2.snp.top)
                    make.centerX.equalTo(self.nodeViwe2)
                }
            })
            self.nodeViweLab2.removeFromSuperview()
            self.nodeViweLab3.removeFromSuperview()
            self.nodeViwe3.removeFromSuperview()
            self.nodeViweLab4.removeFromSuperview()
            self.nodeViwe4.removeFromSuperview()
            self.nodeViweLab1.text = sel.getString("provinceName")
            
        })
        nodeViwe2.callSelBlock(block: { (sel) in
            self.cityCode = sel
            self.getGetDistrictList(cityID: sel.getString("cityID") ?? "", callback: { (list) in
                self.nodeViwe3.nameKey = "districtName"
                bgview.drawView(view: self.nodeViwe3) { (make) in
                    make.left.equalTo(self.nodeViwe2.snp.right)
                    make.width.equalTo(90)
                    make.top.equalToSuperview().offset(90)
                    make.bottom.equalToSuperview()
                }
                self.nodeViwe3.titleArr = list
                bgview.drawLabel(label: self.nodeViweLab3, text: "请选择", fontSize: 13, fontWeight: .regular, textColor: .x333333) { (make) in
                    make.bottom.equalTo(self.nodeViwe3.snp.top)
                    make.centerX.equalTo(self.nodeViwe3)
                }
            })
            self.nodeViweLab3.removeFromSuperview()
            self.nodeViweLab4.removeFromSuperview()
            self.nodeViwe4.removeFromSuperview()
            self.nodeViweLab2.text = sel.getString("cityName")
            self.nodeViweLab2.preferredMaxLayoutWidth = 80
            self.nodeViweLab2.numberOfLines = 2
        })
        nodeViwe3.callSelBlock(block: { (sel) in
            self.districtCode = sel
            self.getGetTownList(districtID: sel.getString("districtID") ?? "", callback: { (list) in
                self.nodeViwe4.nameKey = "townName"
                bgview.drawView(view: self.nodeViwe4) { (make) in
                    make.left.equalTo(self.nodeViwe3.snp.right)
                    make.width.equalTo(140)
                    make.top.equalToSuperview().offset(90)
                    make.bottom.equalToSuperview()
                }
                self.nodeViwe4.titleArr = list
                if list.count == 0 {
                    self._closeButtonClick(button: Button())
                }else{
                    bgview.drawLabel(label: self.nodeViweLab4, text: "请选择", fontSize: 13, fontWeight: .regular, textColor: .x333333) { (make) in
                        make.bottom.equalTo(self.nodeViwe4.snp.top)
                        make.centerX.equalTo(self.nodeViwe4)
                    }
                }
            })
            
            self.nodeViweLab4.removeFromSuperview()
            self.nodeViweLab3.text = sel.getString("districtName")
        })
        nodeViwe4.callSelBlock(block: { (sel) in
            self.townCode = sel
            

            self.nodeViweLab4.text = sel.getString("townName")
            self._closeButtonClick(button: Button())
        })
    }
    
    
    func getGetProvinceList(callback: @escaping ([[String:Any?]]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_GetProvinceList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let data = result.data?.getDictionary("data")?.getDictList("items") {
                    callback(data)
                }
            }
            else {
            }
        }
    }
    
    func getGetCityList(provinceID: String,callback: @escaping ([[String:Any?]]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "provinceID":provinceID]
        API.request(url: .M_GetCityList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let data = result.data?.getDictionary("data")?.getDictList("items") {
                    callback(data)
                }
            }
            else {
            }
        }
    }
    
    func getGetDistrictList(cityID: String,callback: @escaping ([[String:Any?]]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "cityID":cityID]
        API.request(url: .M_GetDistrictList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let data = result.data?.getDictionary("data")?.getDictList("items") {
                    callback(data)
                }
            }
            else {
            }
        }
    }
    
    func getGetTownList(districtID: String,callback: @escaping ([[String:Any?]]) -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "districtID":districtID]
        API.request(url: .M_GetTownList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let data = result.data?.getDictionary("data")?.getDictList("items") {
                    callback(data)
                }
                else {
                    callback([])
                }
            }
            else {
                callback([])
            }
        }
    }
}

// MARK: event & action
extension M_AddressSelView {
    @objc func _closeButtonClick(button: Button) {
        self.removeFromSuperview()
        if callBack != nil {
            callBack!(self)
        }
    }
}

import RxSwift
import RxCocoa

//class OA_Tree_mutipleView: ConstraintsScrollView {
//
//    var selectindexs:[Int]=[]//选中的
//    //定义一个闭包类型
//    typealias selectBlock = (_ selarr : [[String:Any?]]) -> Void
//    //声明一个变量
//    var callBack: selectBlock?
//    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
//    func callSelBlock(block: @escaping selectBlock) {
//        callBack = block
//    }
//
//    //清理视图
//    func clearview() {
//        let chilrenviews = self.contentView.subviews
//        for chilren in chilrenviews {
//            chilren.removeFromSuperview()
//        }
//    }
//
//    //标题数组
//    var titleArr:[[String:Any?]]=[]{
//        didSet{
//            clearview()
//            for i in  0..<titleArr.count{
//                //组装按钮和label
//                let singleselectview:UIView = UIView()
//                self.contentView.addSubview(singleselectview)
//                self.contentView.drawView(view: singleselectview) { (make) in
//                    make.left.right.equalToSuperview()
//                    make.height.equalTo(18)
//                    make.top.equalTo(22*(i+1)+18*i)
//                }
//                let leftBtn:Button=Button()
//                singleselectview.addSubview(leftBtn)
//                self.contentView.drawButton(button: leftBtn,title: titleArr[i].getString("empname"), titleColor: .x333333, fontSize: 13) { (make) in
//                    make.left.equalTo(singleselectview.snp.left).offset(10)
//                    make.top.equalTo(singleselectview.snp.top)
//                }
//                leftBtn.tag=1000+i;
//                leftBtn.setTitleColor(.x333333, for: .normal)
//                leftBtn.setTitleColor(.xFC4C02, for: .selected)
//                leftBtn.addTarget(self, action: #selector(leftBtnClcik), for: UIControl.Event.touchUpInside)
//                leftBtn.hitEdgInsets = .init(top: -10, left: -10, bottom: -10, right: -40)
//
//                let img:UIImageView = UIImageView()
//                singleselectview.addSubview(img)
//                self.contentView.drawImage(imageView: img,named: "home_icon_dagou") { (make) in
//                    make.centerY.equalTo(leftBtn.snp.centerY)
//                    make.right.equalToSuperview().offset(-10)
//                }
//                img.tag=2000+i;
//                img.isHidden = true
//
//                //设置scr的长度
//                if i == titleArr.count-1 {
//                    self.bottomEqualTo(singleselectview, offset: 15)
//                }
//            }
//        }
//    }
//
//    //确认按钮,根据选中的按钮索引做相应的操作
//    @objc func sureBtnClcik(){
//        print("\(selectindexs)")
//    }
//
//    //点击按钮选中或取消
//    @objc func leftBtnClcik(sender:UIButton){
//        sender.isSelected = !sender.isSelected
//        sender.superview?.viewWithTag(sender.tag+1000)?.isHidden = !sender.isSelected
//        let btnTag:Int=sender.tag-1000
//        if sender.isSelected{//选中
//            selectindexs.append(btnTag)//吧按钮的索引存储起来
//        }else {
//            //删除数组中的元素，采用过滤的方法，swift中没有现成f的方法
//            let fiflter:[Int]=selectindexs.filter {
//                $0 != btnTag
//            }
//            selectindexs = fiflter
//        }
//
//        //调用闭包,设置你想传递的参数,调用前先判定一下,是否已实现
//        if callBack != nil {
//            var selarr:[[String:Any?]] = []
//            for sel in selectindexs {
//                selarr.append(titleArr[sel])
//            }
//            callBack!(selarr)
//        }
//    }
//}

/**
 单选框
 */
class OA_Tree_SingView: ConstraintsScrollView {
    
    var selectindex:Int=0//选中的
    var lastbtn:UIButton=UIButton.init()//保存上一个按钮
    
    //定义一个闭包类型
    typealias selectBlock = (_ selarr : [String:Any?]) -> Void
    //声明一个变量
    var callBack: selectBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callSelBlock(block: @escaping selectBlock) {
        callBack = block
    }
    
    //清理视图
    func clearview() {
        let chilrenviews = self.contentView.subviews
        for chilren in chilrenviews {
            chilren.removeFromSuperview()
        }
    }
    
    var nameKey = "text"
    
    //标题数组
    var titleArr:[[String:Any?]]=[]{
        didSet{
            clearview()
            for i in  0..<titleArr.count{
                //组装按钮和label
                let singleselectview:UIView = UIView()
                self.contentView.addSubview(singleselectview)
                self.contentView.drawView(view: singleselectview) { (make) in
                    make.left.right.equalToSuperview()
                    make.height.equalTo(18 + 22)
                    make.top.equalTo(22*(i+1)+18*i - 15)
                }
//                if i != titleArr.count-1 {
                singleselectview.drawView { (make) in
                    make.left.right.bottom.equalToSuperview()
                    make.height.equalTo(0.5)
                    }.backgroundColor = .xD1D1D1
//                }
//                singleselectview.backgroundColor = .red
                
                let leftBtn:Button=Button()
                singleselectview.addSubview(leftBtn)
                self.contentView.drawButton(button: leftBtn,title: titleArr[i].getString(nameKey), titleColor: .x333333, fontSize: 13) { (make) in
                    make.left.right.top.bottom.equalTo(singleselectview)
//                    make.centerX.equalTo(singleselectview)
//                    make.top.equalTo(singleselectview.snp.top)
                }
                leftBtn.tag=1000+i;
                leftBtn.setTitleColor(.x333333, for: .normal)
                leftBtn.setTitleColor(.xFC4C02, for: .selected)
                leftBtn.addTarget(self, action: #selector(leftBtnClcik), for: UIControl.Event.touchUpInside)
//                leftBtn.hitEdgInsets = .init(top: -10, left: -10, bottom: -10, right: -20)
                leftBtn.titleLabel?.numberOfLines = 2
                //设置scr的长度
                if i == titleArr.count-1 {
                    self.bottomEqualTo(singleselectview, offset: 15)
                }
            }
        }
    }
    
    
    //点击按钮选中或取消
    @objc func leftBtnClcik(sender:UIButton){
        let btnTag:Int=sender.tag-1000
        sender.isSelected=true
        lastbtn.isSelected=false
        lastbtn=sender
        selectindex = btnTag
        
        //调用闭包,设置你想传递的参数,调用前先判定一下,是否已实现
        if callBack != nil {
            callBack!(titleArr[selectindex])
        }
    }
}
